package mx.spring.mvc.core;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FrameworkServlet extends HttpServlet {

	private static final long serialVersionUID = -5695207529249558667L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String result="";
		ServletContext sct=this.getServletContext();
		Map<String,String> map=(Map<String, String>) sct.getAttribute("mx_spring");
		String value=map.get(request.getServletPath());
		String[] info=value.split(",");
		String className=info[0];
		String methodName=info[1];
		String methodParam=info[2];
		try {
			Class cls=Class.forName(className);
			Object clsObj=cls.newInstance();
			//注入参数类的属性值
			Class param=Class.forName(methodParam);
			Object paramObj=param.newInstance();
			Field[] fs=param.getDeclaredFields();
			for(Field f:fs){
				f.setAccessible(true);
				f.set(paramObj, request.getParameter(f.getName()));
				f.setAccessible(false);
			}
			//运行方法
			Method method=cls.getDeclaredMethod(methodName, param);
			result=(String) method.invoke(clsObj,paramObj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		PrintWriter pw=response.getWriter();
		pw.println(result);
		pw.flush();
		pw.close();
		/*
		 * 使用服务器端跳转到结果显示页面，这里就不再弄了，直接在Servlet的页面打印输出
		 */
		//request.getRequestDispatcher(resultView).forward(request, response);
	}
}
